package com.yc.book.servlet;

import jakarta.servlet.ServletException;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.FileInputStream;
import java.io.IOException;

@WebServlet({"/images/*"})
public class loadUploadFileServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取请求的URI
        String requestURI = req.getRequestURI();
        //System.out.println("requestURI = " + requestURI);
        //获取上下文路径
        String contextPath = req.getServletContext().getContextPath();
        //System.out.println("contextPath = " + contextPath);
        //截取路径中的相对路径
        String path = requestURI.substring((contextPath + "/images").length());
        //文件的真实路径
        UploadServlet  uploadServlet = new UploadServlet();
        String disPath = uploadServlet.getUploadDir() + path ;
       // System.out.println("disPath = " + disPath);
        //读取文件
        ServletOutputStream out = resp.getOutputStream();
        //获取文件的MINE类型
        String mineType = req.getServletContext().getMimeType(disPath);
        //System.out.println("mineType = " + mineType);
        //如果没有指定MINE类型，那么默认使用application/octet-stream
        resp.setContentType(mineType);
        //try()  后面的括号内容表示在try块结束后会自动关闭的资源
        //out 为什么不关闭？ 因为out是从resp中获取的，resp由服务器创建，服务器会自动关闭
        try (FileInputStream fis = new FileInputStream(disPath)) {
                byte[] buffer = new byte[fis.available()];
                //count 表示读取的字节数
               int count ;
               while ((count = fis.read(buffer)) != -1) {
                   out.write(buffer, 0, count);
               }
        }
    }


}
